#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/msg.h>
#include <sys/stat.h>

using namespace std;

const int BUFSIZE = 1023;
const char *MSG_FILE = "/";

struct MsgType
{
	long mtype;				/* message type, must be > 0 */
	char mtext[BUFSIZE+1];	/* message data */
};

int main(int argc, char **argv)
{
	struct MsgType msg;
	key_t key;
	int msgId;

	if(argc != 2)
	{
		cout << "Usage error: " << argv[0] << endl;
		exit(1);
	}

	if ((key = ftok(MSG_FILE, 'a')) == -1)
	{
		cout << "Creat Key Error: " << strerror(errno) << endl;
		exit(1);
	}

	cout << "Key: " << (int)key << endl;

	if((msgId = msgget(key, S_IRUSR|S_IWUSR)) == -1)
	{
		cout << "Get Message Error: " << strerror(errno) << endl;
		exit(1);
	}

	cout << "Messge ID: " << msgId << endl;

	msg.mtype = 1;
	strncpy(msg.mtext, argv[1], BUFSIZE);
	msgsnd(msgId, &msg, sizeof(struct MsgType) - sizeof(long), 0);
	memset(&msg, '\0', sizeof(struct MsgType));
	msgrcv(msgId, &msg, sizeof(struct MsgType) - sizeof(long), 2, 0);

	cout << "Client receive: " << msg.mtext << endl;

	return 0;
}

